package com.guigui.gulimall.product.exceptionHandler;

import com.guigui.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

/**
 * @author ：xin
 * @date ：Created in 2021/7/27 20:49
 * @description：
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.guigui.gulimall.product.controller")
public class GlobalException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R controllerException(MethodArgumentNotValidException e){
        log.error("发生错误数据:{},详细信息：{}",e.getClass(),e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        HashMap<String, String> errorMap = new HashMap<>();
        fieldErrors.forEach(error -> {
            errorMap.put(error.getField(),error.getDefaultMessage());
        });
        return R.error(400,"提交数据有误").put("data",errorMap);
    }

}
